import os 

def get_queue_list(queue):
    queue_node_list = os.popen(f"qstat -fQ {queue} | grep -Po 'n\d{{3}}'").readlines()
    for i in range(len(queue_node_list)):
        queue_node_list[i] = queue_node_list[i].strip('\n')
    return queue_node_list

def get_pbs_free_nodes(myconfig):
    subinfo = myconfig["subinfo"]
    queue_node_list = get_queue_list(subinfo["queue"])
    nodeinfo = subinfo["nodeinfo"]
    free_node = []
    if nodeinfo["specify_node_list"] is not None:
        free_node += nodeinfo["specify_node_list"]
    else:
        sub_task = os.popen("pestat | awk \'$2==\"free\" && $8==\"0/0\" && $9==0 {print $1}\'").readlines()
        for i in range(len(sub_task)):
            sub_task[i] = sub_task[i].strip('\n')
        free_node = sub_task
        if(len(free_node)*28 < subinfo["processinfo"]["np_end"]):
            if nodeinfo["specify_node_list"] is not None:
                free_node += nodeinfo["specify_node_list"]
                free_node = free_node.sort() 
    # 取交集
    free_node = list(set(free_node).intersection(set(queue_node_list)))
    
    # #for testing
    # free_node = ["n20", "n50", "n100", "n424"]

    if nodeinfo["excluded_nodes_list"] is not None:
        # 取余集
        free_node = list(set(free_node).difference(set(nodeinfo["excluded_nodes_list"])))
    if(len(free_node)*28 < subinfo["processinfo"]["np_end"] and nodeinfo["node_list_order"] != "normal"):
        print("You need num of nodes is too many!")
        exit(0)
    else:
        subinfo["nodeinfo"]["free_nodes"] = free_node